package com.github.gdxmap.geo.projection;

import com.github.gdxmap.geo.LatLng;
import com.github.gdxmap.geometry.Point;

import org.osgeo.proj4j.CRSFactory;
import org.osgeo.proj4j.CoordinateReferenceSystem;
import org.osgeo.proj4j.CoordinateTransform;
import org.osgeo.proj4j.CoordinateTransformFactory;
import org.osgeo.proj4j.ProjCoordinate;

/**
 * 默认为墨卡托投影
 * 推荐WGS 84 / World Mercator 3395
 * Created by free on 2016/12/6 0006.
 */
public class MercatorProjection {
    CoordinateReferenceSystem srcSystem;
    CoordinateReferenceSystem distSystem;

    public MercatorProjection(){
        CRSFactory crsFactory=new CRSFactory();

        srcSystem=crsFactory.createFromName("epsg:4326");
        distSystem=crsFactory.createFromName("epsg:3395");
    }

    public MercatorProjection(String srcEPSG,String distEPSG){
        CRSFactory crsFactory=new CRSFactory();

        srcSystem=crsFactory.createFromName(srcEPSG);
        distSystem=crsFactory.createFromName(distEPSG);
    }
    public Point project(double lat,double lng){
        return project(new LatLng(lat,lng));
    }
    /**
     * 投影变换
     * @param latLng
     * @return
     */
    public Point project(LatLng latLng){
        Point point=new Point();

        ProjCoordinate srcCoordinate=new ProjCoordinate();
        ProjCoordinate distCoordinate=new ProjCoordinate();

        srcCoordinate.setValue(latLng.getLat(),latLng.getLng());

        CoordinateTransform transform = new CoordinateTransformFactory().createTransform(srcSystem,distSystem);
        transform.transform(srcCoordinate,distCoordinate);

        point.set((int)distCoordinate.x,(int) distCoordinate.y);

        return point;
    }

    /**
     * 逆投影变换
     * @param point
     * @return
     */
    public LatLng unProject(Point point){
        LatLng latLng=new LatLng();

        ProjCoordinate srcCoordinate=new ProjCoordinate();
        ProjCoordinate distCoordinate=new ProjCoordinate();

        srcCoordinate.setValue(point.x,point.y);

        CoordinateTransform transform = new CoordinateTransformFactory().createTransform(distSystem,srcSystem);
        transform.transform(srcCoordinate,distCoordinate);

        latLng.setLat(distCoordinate.x);
        latLng.setLng(distCoordinate.y);

        return latLng;
    }
}
